package com.kly.cashmall.module.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonArray;
import com.kly.cashmall.R;
import com.kly.cashmall.base.BaseBarActivity;
import com.kly.cashmall.base.app_action.ActionBuildHelper;
import com.kly.cashmall.base.app_action.ActionHeads;
import com.kly.cashmall.base.app_action.BaseActionHelper;
import com.kly.cashmall.bean.ExtensionDetailBean;
import com.kly.cashmall.bean.LoanDetailBean;
import com.kly.cashmall.bean.LoanDetailBillVOSBean;
import com.kly.cashmall.bean.RazorpayInfoBean;
import com.kly.cashmall.event.HomeEvent;
import com.kly.cashmall.framework.mvp.PresenterLifeCycle;
import com.kly.cashmall.module.order.adapter.GeneralInformationDisplayAdapter;
import com.kly.cashmall.module.order.adapter.LoanPlanOfRepayAdapter;
import com.kly.cashmall.module.order.presenter.LoanDetailsPresenter;
import com.kly.cashmall.module.order.presenter.LoanDetailsViewer;
import com.kly.cashmall.module.repay.RepayResultActivity;
import com.kly.cashmall.module.web.WebViewActivity;
import com.kly.cashmall.popup.ExceedingPopupWindow;
import com.kly.cashmall.popup.SystemTipWithTitlePopup;
import com.kly.cashmall.utils.data.CollectionUtils;
import com.kly.cashmall.utils.function.CommonUtils;
import com.kly.cashmall.utils.function.GlideUtils;
import com.kly.cashmall.utils.data.TextUtil;
import com.kly.cashmall.utils.function.ToastUtil;
import com.kly.cashmall.utils.ViewHolder;

import org.greenrobot.eventbus.EventBus;


/**
 * @author
 */
public class LoanDetailsActivity extends BaseBarActivity implements LoanDetailsViewer, LoanPlanOfRepayAdapter.OnClickListener {

    private static String TRADENO = "tradeNo";
    private static final int PAYMENT_FOR_RESULT = 10001;

    @PresenterLifeCycle
    LoanDetailsPresenter presenter = new LoanDetailsPresenter(this);
    private String tradeNo;
    private ListView mOrderDeatailList;
    private GeneralInformationDisplayAdapter mAdapter;
    private ConstraintLayout mOrderStatus;
    private LoanPlanOfRepayAdapter mRepayAdapter;
    private RecyclerView mPlanOfRepayList;


    private boolean rpShow = false;
    private JsonArray billNos;
    private String billNo;

    public static Intent newIntent(Context context, String tag) {
        Intent intent = new Intent(context, LoanDetailsActivity.class);
        intent.putExtra(TRADENO, tag);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return intent;
    }

    @Override
    protected void setView(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_loan_details);
        setTitle(this.getResources().getString(R.string.order_details));
        tradeNo = getIntent().getStringExtra(TRADENO);

        mOrderDeatailList = bindView(R.id.order_detail_list);
        mAdapter = new GeneralInformationDisplayAdapter(this);
        mOrderDeatailList.setAdapter(mAdapter);
        mOrderStatus = bindView(R.id.order_status);
        mPlanOfRepayList = bindView(R.id.repayment_plan_list);
        mRepayAdapter = new LoanPlanOfRepayAdapter(this);
        mPlanOfRepayList.setLayoutManager(new LinearLayoutManager(this));
        mPlanOfRepayList.setAdapter(mRepayAdapter);

    }

    @Override
    protected void loadData() {
    }

    @Override
    public void getOrderDetailSuccess(LoanDetailBean orderDetailBean) {
        mOrderStatus.removeAllViews();
        if (orderDetailBean.getOrderInfo() != null) {
            switch (orderDetailBean.getOrderInfo().getStatus()) {
                case 0:
                    setCompleted(orderDetailBean.getOrderInfo());
                    break;
                case 1:
                case 10:
                    setReviewing(orderDetailBean.getOrderInfo());
                    break;
                case 2:
                case 5:
                    setPayFailed(orderDetailBean.getOrderInfo());
                    break;
                case 3:
                    setWaiting(orderDetailBean);
                    break;
                case 4:
                    setRefused(orderDetailBean.getOrderInfo());
                    break;
                case 6:
                    setOverdue(orderDetailBean);
                    break;
                case 11:
                    setWaitingWithdrawal(orderDetailBean);
                    break;
                default:
                    break;
            }
        }
        billNo = orderDetailBean.getOrderInfo().getBillNo();
        GlideUtils.loadImage(this, orderDetailBean.getCategoryLogo(),bindView(R.id.plan_of_detail_logo));
        bindText(R.id.plan_of_detail_title, orderDetailBean.getCategoryName());
        bindText(R.id.plan_of_detail_date, "Apply Date: " + orderDetailBean.getOrderApplyDate());
        if (!CollectionUtils.isEmpty(orderDetailBean.getOrderFieldDetails())) {
            bindView(R.id.plan_of_detail, true);
            mAdapter.setOrderFieldDetailsBean(orderDetailBean.getOrderFieldDetails());
        }

        if (!CollectionUtils.isEmpty(orderDetailBean.getRepaymentPlans()) && orderDetailBean.getOrderInfo().getStatus() != 9) {
            bindView(R.id.plan_of_repay, true);
            bindText(R.id.tv_plan_total, "Total " + orderDetailBean.getRepaymentPlans().size());
            mRepayAdapter.setList(orderDetailBean.getRepaymentPlans());
            bindView(R.id.cl_plan_total, v -> {
                bindView(R.id.repayment_plan_list, !rpShow);
                rpShow = !rpShow;
                ((ImageView) bindView(R.id.img_plan_total)).setImageResource(rpShow ? R.mipmap.ic_details_fold : R.mipmap.ic_details_unfold);
            });
        }
        if (orderDetailBean.getOrderWithdrawButton() != null){
            bindView(R.id.withdraw_bottom,true);
        }else {
            bindView(R.id.withdraw_bottom,false);
        }

    }

    /**
     * 审核中
     *
     * @param statusInfo
     */
    private void setReviewing(LoanDetailBean.StatusInfo statusInfo) {
        View view = LayoutInflater.from(this).inflate(R.layout.include_layout_reviewing, null);
        ViewHolder holder = ViewHolder.getHolder(view);
        holder.setText(R.id.reviewing_status, statusInfo.getStatusText());
        holder.setText(R.id.reviewing_tips, statusInfo.getTips());
        mOrderStatus.addView(view);
    }

    /**
     * 订单拒绝
     *
     * @param statusInfo
     */
    private void setRefused(LoanDetailBean.StatusInfo statusInfo) {
        View view = LayoutInflater.from(this).inflate(R.layout.include_layout_refused, null);
        ViewHolder holder = ViewHolder.getHolder(view);
        holder.setText(R.id.refused_status, statusInfo.getStatusText());
        holder.setText(R.id.refused_tips, statusInfo.getTips());
        mOrderStatus.addView(view);
    }

    /**
     * 逾期
     *
     * @param detailBean
     */
    private void setOverdue(LoanDetailBean detailBean) {
        View view = LayoutInflater.from(this).inflate(R.layout.include_layout_overdue, null);
        ViewHolder holder = ViewHolder.getHolder(view);
        LoanDetailBean.StatusInfo statusInfo = detailBean.getOrderInfo();
        SpannableString string = new SpannableString(statusInfo.getRepaymentAmount());
        if (statusInfo.getRepaymentAmount().contains("₹")) {
            string.setSpan(new RelativeSizeSpan(0.78f), statusInfo.getRepaymentAmount().indexOf("₹"), statusInfo.getRepaymentAmount().indexOf("₹") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        holder.setText(R.id.overdue_plan_amount, string);
        holder.setText(R.id.overdue_status, statusInfo.getStatusText());
        holder.setText(R.id.overdue_deta, statusInfo.getRepaymentDate());
        holder.setText(R.id.overdue_apply, statusInfo.getButtonText());
        holder.setText(R.id.overdue_plan, "Plan " + statusInfo.getCurrentPeriod());
        holder.setText(R.id.repay_pricipal, "Principal: " + statusInfo.getPrincipal());
        holder.setText(R.id.repay_interest, "Interest: " + statusInfo.getInterest());
        if (!TextUtil.isEmpty(statusInfo.getOverdueFee())) {
            holder.setText(R.id.repay_over_fee, "OverdueFee: " + statusInfo.getOverdueFee());
        }

        if (detailBean.getMsgInfo() != null) {
            holder.setVisible(R.id.cl_waring, true);
            GlideUtils.loadImage(this, detailBean.getMsgInfo().getImgUrl(),holder.getView(R.id.waring_icon));
            holder.setText(R.id.warning_title, detailBean.getMsgInfo().getTitle());
            holder.setText(R.id.warning_tips, detailBean.getMsgInfo().getMsg());
        } else {
            holder.setVisible(R.id.cl_waring, false);
        }
        holder.setClickListener(R.id.overdue_apply, view1 -> {
            billNos = new JsonArray();
            billNos.add(statusInfo.getBillNo());
            presenter.repayRezorpayPost(tradeNo);
        });
        holder.setVisible(R.id.btn_immediate_exceeding,detailBean.getOrderInfo().isShowExtension());
        holder.setClickListener(R.id.btn_immediate_exceeding, view1 -> {
            billNos = new JsonArray();
            billNos.add(statusInfo.getBillNo());
            presenter.getExtensionDetail(billNos);
        });
        mOrderStatus.addView(view);
    }

    /**
     * 用户审核通过后，打款失败/high mark填写
     *
     * @param statusInfo
     */
    private void setPayFailed(LoanDetailBean.StatusInfo statusInfo) {
        View view = LayoutInflater.from(this).inflate(R.layout.include_layout_payfailed, null);
        ViewHolder holder = ViewHolder.getHolder(view);
        holder.setText(R.id.pay_failed_status, statusInfo.getStatusText());
        holder.setText(R.id.pay_failed_tips, statusInfo.getTips());
        holder.setText(R.id.pay_failed_apply, statusInfo.getButtonText());
        holder.setClickListener(R.id.pay_failed_apply, view1 -> {
            BaseActionHelper.with(this).handleAction(statusInfo.getJumpUrl());
        });
        mOrderStatus.addView(view);
    }


    /**
     * 订单完结状态
     *
     * @param detailBean
     */
    private void setCompleted(LoanDetailBean.StatusInfo detailBean) {
        View view = LayoutInflater.from(this).inflate(R.layout.include_layout_completed, null);
        ViewHolder holder = ViewHolder.getHolder(view);
        holder.setText(R.id.completed_status, detailBean.getStatusText());
        holder.setText(R.id.completed_tips, detailBean.getTips());
        holder.setText(R.id.completed_deta, detailBean.getRepaymentDate());
        holder.setText(R.id.completed_apply, detailBean.getButtonText());
        holder.setClickListener(R.id.completed_apply, view1 -> {
            BaseActionHelper.with(this).handleAction(detailBean.getJumpUrl());
        });
        mOrderStatus.addView(view);
    }


    /**
     * 待还款状态
     *
     * @param detailBean
     */
    private void setWaiting(LoanDetailBean detailBean) {
        View view = LayoutInflater.from(this).inflate(R.layout.include_layout_waiting, null);
        ViewHolder holder = ViewHolder.getHolder(view);
        LoanDetailBean.StatusInfo statusInfo = detailBean.getOrderInfo();
        SpannableString string = new SpannableString(statusInfo.getRepaymentAmount());
        if (statusInfo.getRepaymentAmount().contains("₹")) {
            string.setSpan(new RelativeSizeSpan(0.78f), statusInfo.getRepaymentAmount().indexOf("₹"), statusInfo.getRepaymentAmount().indexOf("₹") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        holder.setText(R.id.waiting_plan_amount, string);
        holder.setText(R.id.waiting_status, statusInfo.getStatusText());
        holder.setText(R.id.waiting_plan, "Plan " + statusInfo.getCurrentPeriod());
        holder.setText(R.id.waiting_deta, statusInfo.getRepaymentDate());
        holder.setText(R.id.waiting_apply, statusInfo.getButtonText());
        if (detailBean.getMsgInfo() != null) {
            holder.setVisible(R.id.cl_waring, true);
            GlideUtils.loadImage(this, detailBean.getMsgInfo().getImgUrl(),holder.getView(R.id.waring_icon));
            holder.setText(R.id.warning_title, detailBean.getMsgInfo().getTitle());
            holder.setText(R.id.warning_tips, detailBean.getMsgInfo().getMsg());
        } else {
            holder.setVisible(R.id.cl_waring, false);
        }
        holder.setClickListener(R.id.waiting_apply, view1 -> {
            billNos = new JsonArray();
            billNos.add(statusInfo.getBillNo());
            presenter.repayRezorpayPost(tradeNo);
        });
        mOrderStatus.addView(view);
    }

    /**
     * 打款中
     *
     * @param statusInfo
     */
    private void setTransefering(LoanDetailBean.StatusInfo statusInfo) {
        View view = LayoutInflater.from(this).inflate(R.layout.include_layout_transefering, null);
        ViewHolder holder = ViewHolder.getHolder(view);
        holder.setText(R.id.transefer_status, statusInfo.getStatusText());
        holder.setText(R.id.transefer_tips, statusInfo.getTips());
        mOrderStatus.addView(view);
    }

    /**
     * 待提现
     *
     * @param detailBean
     */
    private void setWaitingWithdrawal(LoanDetailBean detailBean) {
        LoanDetailBean.OrderWithdrawInfo withdrawInfo = detailBean.getOrderWithdrawInfo();
        View view = LayoutInflater.from(this).inflate(R.layout.include_layout_waiting_withdrawal, null);
        ViewHolder holder = ViewHolder.getHolder(view);
        holder.setText(R.id.withdraw_status,withdrawInfo.getTitle());
        holder.setText(R.id.withdraw_amount, CommonUtils.setSymbol(withdrawInfo.getPrincipal(),"₹",0.5f));
        SpannableString spannableString = CommonUtils.setHighLightTwo(withdrawInfo.getTips(), withdrawInfo.getHighlightTextList().get(0),withdrawInfo.getHighlightTextList().get(1), getResources().getColor(R.color.color_D42522));
        holder.setText(R.id.withdraw_tips,spannableString);
        holder.setText(R.id.next_loan_amount, CommonUtils.setSymbol(withdrawInfo.getNextPrincipal(),"₹",0.75f));
        holder.setText(R.id.next_loan_title,withdrawInfo.getNextTitle());
        holder.setText(R.id.next_loan_tips,withdrawInfo.getNextTips());
        bindView(R.id.plan_of_repay,false);

        if (detailBean.getOrderWithdrawButton() != null){
            bindView(R.id.withdraw_bottom,true);
            bindText(R.id.order_bottom_title,detailBean.getOrderWithdrawButton().getButtonText1());
            bindText(R.id.order_bottom_tip,detailBean.getOrderWithdrawButton().getButtonText2());
            bindView(R.id.withdraw_bottom,v -> {
                presenter.getOrderWithdraw(tradeNo);
            });
        }else {
            bindView(R.id.withdraw_bottom,false);
        }
        mOrderStatus.addView(view);
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.getOrderDetail(tradeNo);
    }

    @Override
    public void repayPostSuccess(RazorpayInfoBean rezorpayInfoBean) {
        if (!TextUtil.isEmpty(rezorpayInfoBean.getPlatform())) {
            if (rezorpayInfoBean.getPaymentLink().contains("URL/Result/")) {
                String url = rezorpayInfoBean.getPaymentLink().substring("URL/Result/".length());

                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("URL", url);
                startActivityForResult(intent, PAYMENT_FOR_RESULT);
            }else {
                BaseActionHelper.with(getActivity()).handleAction(ActionBuildHelper.with(rezorpayInfoBean.getPaymentLink()).put("type", "0").put("billNo", billNo).getAction());
            }
        }
    }


    @Override
    public void getOrderWithdrawSuccess(String msg) {
        ToastUtil.showToast(msg);
        EventBus.getDefault().post(new HomeEvent());
        presenter.getOrderDetail(tradeNo);
    }

    @Override
    public void getExtensionDetailSuccess(ExtensionDetailBean bean) {
        ExceedingPopupWindow popupWindow = new ExceedingPopupWindow(getActivity(),bean,() -> {
            presenter.repayRezorpayPost(tradeNo);

        });
        popupWindow.setPopupGravity(Gravity.CENTER);
        popupWindow.showPopupWindow();
    }

    @Override
    public void clickListener(View view, LoanDetailBillVOSBean billVOS) {
        if (billVOS.isPaid()) {
            BaseActionHelper.with(this).handleAction(ActionBuildHelper.with(ActionHeads.LMActionRepayDetails).put("billNo", billVOS.getBillNo()).getAction());
        } else {
            billNo = billVOS.getBillNo();
            billNos = new JsonArray();
            billNos.add(billVOS.getBillNo());
            presenter.repayRezorpayPost(tradeNo);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PAYMENT_FOR_RESULT) {
            SystemTipWithTitlePopup popup = new SystemTipWithTitlePopup(getActivity());
            popup.setTitleText(getString(R.string.pop_common_title_hint));
            popup.setMessageText("Repayment done?");
            popup.setMessageTextSize(16);
            popup.setCancelText("No");
            popup.setConfirmText("Yes");
            popup.setOutSideDismiss(false);
            popup.setOutSideTouchable(false);
            popup.setConfirmClick(view -> {
                startActivity(RepayResultActivity.callIntent(getActivity(), billNo,0));
            });
            popup.setPopupGravity(Gravity.CENTER).showPopupWindow();
        }
    }
}
